package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.dto.TeachplanDTO;
import com.xuecheng.api.content.model.dto.TeachplanMediaDTO;
import com.xuecheng.api.media.model.dto.MediaDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.CourseModeEnum;
import com.xuecheng.common.enums.content.TeachPlanEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.agent.MediaApiAgent;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.convert.TeachplanConvert;
import com.xuecheng.content.convert.TeachplanMediaConvert;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.Teachplan;
import com.xuecheng.content.entity.TeachplanMedia;
import com.xuecheng.content.entity.ext.TeachplanNode;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private TeachplanMediaService teachplanMediaService;

    @Autowired
    private MediaApiAgent mediaApiAgent;
   /*
    * 业务分析：
    *   1.判断关键数据
    *       courseId companyId
    *   2.判断业务数据
    *       课程基础信息
    *           判断是否存在
    *           判断是否是同一家教学机构
    *           判断是否删除
    *   3.根据Courseid查询课程计划数据
    *   4.通过java的递归生成课程计划树形结构
    *   5.将数据转为dto并返回
    * */
    public TeachplanDTO queryTreeNodesByCourseId(Long courseId, Long companyId) {
        // 1.判断关键数据
        //      courseId companyId
        if (ObjectUtils.isEmpty(courseId)||
                ObjectUtils.isEmpty(companyId)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        //  2.判断业务数据
        //      课程基础信息
        //          判断是否存在
        //          判断是否是同一家教学机构
        //          判断是否删除
        LambdaQueryWrapper<CourseBase> baseQueryWrapper = new LambdaQueryWrapper<>();
        baseQueryWrapper.eq(CourseBase::getId, courseId);
        baseQueryWrapper.eq(CourseBase::getCompanyId, companyId);
        CourseBase courseBase = courseBaseService.getOne(baseQueryWrapper);
        if (ObjectUtils.isEmpty(courseBase)) {
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }
        Integer status = courseBase.getStatus();
        if (!(CommonEnum.USING_FLAG.getCodeInt().equals(status))) {
            ExceptionCast.cast(ContentErrorCode.E_120021);
        }
        //  3.根据Courseid查询课程计划数据
        TeachplanMapper baseMapper = this.getBaseMapper();
        List<TeachplanNode> nodes = baseMapper.selectTreeNodesByCourseId(courseId);
        //  4.通过java的递归生成课程计划树形结构

        TeachplanDTO teachplanDTO = null;

        if (ObjectUtils.isEmpty(nodes)) {
            teachplanDTO = new TeachplanDTO();
        } else {
            TeachplanNode rootNode = nodes.remove(0);
            generateTreeNodes(rootNode,nodes);
            teachplanDTO = TeachplanConvert.INSTANCE.node2dto(rootNode);
        }
        //  5.将数据转为dto并返回
        return teachplanDTO;
    }
    private void generateTreeNodes(TeachplanNode parentNode, List<TeachplanNode> nodes) {
        // 1.判断父级集合是否为空，如果为空需要创建
        if (CollectionUtils.isEmpty(parentNode.getChildrenNodes())) {
            parentNode.setChildrenNodes(new ArrayList<>(8));
        }
        // 2.循环遍历集合生成树形结构
        for (TeachplanNode node : nodes) {
            // 2.1 判断node是否和parentnode有关联，如果有关联将node存放到parentNode集合中
            if (ObjectUtils.nullSafeEquals(parentNode.getId(),node.getParentid())) {
                parentNode.getChildrenNodes().add(node);
                // 2.2 生成node集合数据
                // 如果是第三级课程计划，无需递归
                if (!(TeachPlanEnum.THIRD_LEVEL.equals(node.getGrade()))) {
                    generateTreeNodes(node, nodes);
                } else {
                    Long teachplanId = node.getId();
                    LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TeachplanMedia::getTeachplanId, teachplanId);
                    TeachplanMedia teachplanMedia = teachplanMediaService.getOne(queryWrapper);

                    if (!(ObjectUtils.isEmpty(teachplanMedia))) {
                        node.setTeachplanMedia(teachplanMedia);
                    }


                }
            }
        }
    }


    @Transactional
    public TeachplanDTO createOrModifyTeachPlan(TeachplanDTO dto, Long companyId) {
        TeachplanDTO resultDTO = null;

        // 1.判断业务操作
        //      有teachplanid-->修改
        //      没有teachplanid-->新增
        if (ObjectUtils.isEmpty(dto.getTeachPlanId())) {
            //      没有teachplanid-->新增
            resultDTO = createTeachplan(dto,companyId);
        } else {
            //      有teachplanid-->修改
            resultDTO = modifyTeachplan(dto,companyId);
        }
        return resultDTO;
    }

    private TeachplanDTO modifyTeachplan(TeachplanDTO dto, Long companyId) {
        //1.判断关键数据
        //     课程id
        //     课程计划名称
        //     教学机构id
        //     父级id
        //     是否免费
        if (ObjectUtils.isEmpty(dto.getParentid()) || StringUtil.isBlank(dto.getIsPreview())) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        CourseBaseDTO courseBase = verifyTeachplanMsg(dto, companyId);
        //2.判断业务数据
        Teachplan teachplan = this.getById(dto.getTeachPlanId());

        if (ObjectUtils.isEmpty(teachplan)) {
            ExceptionCast.cast(ContentErrorCode.E_120402);
        }

        Long parentid = teachplan.getParentid();

        if (TeachPlanEnum.FIRST_PARENTID_FLAG.equals(parentid)) {
            ExceptionCast.cast(ContentErrorCode.E_120017);
        }
        // 3.将课程计划信息保存
        LambdaUpdateWrapper<Teachplan> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Teachplan::getPname, dto.getPname());
        updateWrapper.set(Teachplan::getIsPreview, dto.getIsPreview());
        updateWrapper.set(Teachplan::getStartTime, dto.getStartTime());
        updateWrapper.set(Teachplan::getEndTime, dto.getEndTime());
        updateWrapper.set(Teachplan::getChangeDate, dto.getChangeDate());

        updateWrapper.eq(Teachplan::getId, dto.getTeachPlanId());

        boolean result = this.update(updateWrapper);

        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120407);
        }

        Teachplan po = this.getById(dto.getTeachPlanId());
        TeachplanDTO resultDTO = TeachplanConvert.INSTANCE.entity2dto(po);

        return resultDTO;
    }

    private TeachplanDTO createTeachplan(TeachplanDTO dto, Long companyId) {
        //1.判断关键数据
        //     课程计划的名称不能为空
        //     课程id不能为空
        //     教学机构id不能为空
        if (ObjectUtils.isEmpty(dto.getPname())||
                ObjectUtils.isEmpty(dto.getCourseId())||
                ObjectUtils.isEmpty(companyId)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        // 2.判断业务数据
        //     课程基础信息
        //         判断是否存在
        //         判断是否是同一家教学机构
        //         判断是否删除
        //         判断审核状态：未提交、审核未通过
        CourseBaseDTO courseBase = courseBaseService.getCourseBaseById(dto.getCourseId(), companyId);
        String auditStatus = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus)) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }
        // 3.获得新增课程计划的父级数据
        //     给新增课程计划赋值
        //         grade：父级的grade+1
        //         parentid：父级的id
        //         orderby：select max(order) from teachplan where parentid = 父级id
        Teachplan parentNode = generateParentNode(dto,courseBase);
        int childrenGrade = parentNode.getGrade() + 1;
        dto.setGrade(childrenGrade+"");
        dto.setParentid(parentNode.getId());

        TeachplanMapper baseMapper = this.getBaseMapper();
        Integer orderBy = baseMapper.selectOrderByParentId(parentNode.getId());

        // 如果查询出orderBy为null --> 默认赋值为1
        // 如果查询出orderBy为不null --> orderBy+1
        if (ObjectUtils.isEmpty(orderBy)) {
            dto.setOrderby(TeachPlanEnum.FIRST_LEVEL);
        } else {
            dto.setOrderby(orderBy+1);
        }
        // 4.将dto转为po并保存到数据库中
        Teachplan teachplan = TeachplanConvert.INSTANCE.dto2entity(dto);
        boolean save = this.save(teachplan);
        if (!save) {
            ExceptionCast.cast(ContentErrorCode.E_120407);
        }
        // 5.将数据库最新的数据转为dto并返回
        Teachplan po = this.getById(teachplan.getId());
        TeachplanDTO teachplanDTO = TeachplanConvert.INSTANCE.entity2dto(po);

        return teachplanDTO;
    }

    private Teachplan generateParentNode(TeachplanDTO dto, CourseBaseDTO courseBase) {

        //1.判断新增数据是二级还是三级课程计划
        //     判断新增数据是否有parentId值
        //         如果有：三级课程计划
        //         如果没有：二级课程计划
        Long parentid = dto.getParentid();
        if (ObjectUtils.isEmpty(parentid)) {
            // 2.获得二级课程计划的父级数据
            //     查询数据库获得一级课程计划：courseId、parentid=0
            //         如果没有：自动创建并保存数据--数据来源 coursebase
            //         如果有：直接返回
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, courseBase.getCourseBaseId());
            queryWrapper.eq(Teachplan::getParentid, TeachPlanEnum.FIRST_PARENTID_FLAG);

            Teachplan rootParent = this.getOne(queryWrapper);

            if (ObjectUtils.isEmpty(rootParent)) {

                rootParent = new Teachplan();
                rootParent.setPname(courseBase.getName());
                rootParent.setParentid(new Long(TeachPlanEnum.FIRST_PARENTID_FLAG));
                rootParent.setGrade(TeachPlanEnum.FIRST_LEVEL);
                rootParent.setDescription(courseBase.getDescription());
                rootParent.setOrderby(TeachPlanEnum.FIRST_LEVEL);
                rootParent.setCourseId(courseBase.getCourseBaseId());
                boolean save = this.save(rootParent);

                if (!save) {
                    ExceptionCast.cast(ContentErrorCode.E_120415);
                }
            }

            return rootParent;

        } else {
            // 3.获得三级课程计划的父级数据
            //     查询数据库获得二级课程计划：parentId
            //         如果没有：直接抛出异常
            //         如果有：直接返回
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getId, parentid);

            Teachplan teachplan = this.getOne(queryWrapper);

            if (ObjectUtils.isEmpty(teachplan)) {
                ExceptionCast.cast(ContentErrorCode.E_120408);
            }

            return teachplan;
        }
    }

    private CourseBaseDTO verifyTeachplanMsg(TeachplanDTO dto, Long companyId) {

        //1.判断关键数据
        if (ObjectUtils.isEmpty(companyId)||
                StringUtil.isBlank(dto.getPname())||
                ObjectUtils.isEmpty(dto.getCourseId())
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        Long courseId = dto.getCourseId();
        // 2.判断业务数据
        return getCourseAndVerify(companyId, courseId);
    }

    private CourseBaseDTO getCourseAndVerify(Long companyId, Long courseId) {
        //     课程基础信息
        //         判断是否存在
        //         判断是否同一家机构
        //         判断是否删除
        //         判断课程基础信息审核状态：未提交和审核未通过
        CourseBaseDTO courseBase = courseBaseService.getCourseBaseById(courseId, companyId);

        String auditStatus = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)
        ) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }
        return courseBase;
    }

    @Transactional
    public void removeTeacherPlan(Long teachPlanId, Long companyId) {
        //1.判断数据合法性(课程计划、课程是否存在，公司id是否一致)
        Teachplan teachplan = this.getById(teachPlanId);
        if (ObjectUtils.isEmpty(teachplan)) {
            ExceptionCast.cast(ContentErrorCode.E_120402);
        }
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        if (ObjectUtils.isEmpty(courseBase)) {
            ExceptionCast.cast(ContentErrorCode.E_120013);
        }
        if (!(ObjectUtils.nullSafeEquals(courseBase.getCompanyId(), companyId))) {
            ExceptionCast.cast(CommonErrorCode.E_100108);
        }
        //2.根据课程计划等级进行业务判断
        if (teachplan.getGrade().equals(TeachPlanEnum.SECEND_LEVEL)) {
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachPlanId);
            //此处的count是父id是二级课程计划的（也就是三级课程计划）的数量
            int count = this.count(queryWrapper);
            if (count > 0) {
                ExceptionCast.cast(ContentErrorCode.E_120409);
            } else {
                //判断三级课程计划是否关联课程媒资信息
                LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
                mediaLambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId, teachplan);
                int mediaCount = teachplanMediaService.count(mediaLambdaQueryWrapper);
                if (mediaCount > 0) {
                    ExceptionCast.cast(ContentErrorCode.E_120414);
                }
            }
        }
        //根据id删除课程计划
        this.removeById(teachPlanId);
    }

    @Transactional
    public TeachplanMediaDTO associateMedia(TeachplanMediaDTO dto, Long companyId) {
        //1.判断关键数据
        if (ObjectUtils.isEmpty(companyId)||
                ObjectUtils.isEmpty(dto.getTeachplanId())||
                ObjectUtils.isEmpty(dto.getMediaId())
            ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        //2.1判断业务数据
        Teachplan teachplan = this.getById(dto.getTeachplanId());
        if (ObjectUtils.isEmpty(teachplan)) {
            ExceptionCast.cast(CommonErrorCode.E_100104);
        }
        Integer grade = teachplan.getGrade();
        if (!(TeachPlanEnum.THIRD_LEVEL.equals(grade))) {
            ExceptionCast.cast(ContentErrorCode.E_120410);
        }
        //2.2判断课程基本信息
        Long courseId = teachplan.getCourseId();

        CourseBaseDTO courseBaseDTO = courseBaseService.getCourseBaseById(courseId, companyId);
        String auditStatus = courseBaseDTO.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }
        //判断课程类型是否录播
        String teachmode = courseBaseDTO.getTeachmode();
        if (CourseModeEnum.COURSE_MODE_RECORD_STATUS.getCode().equals(teachmode)) {
            ExceptionCast.cast(ContentErrorCode.E_120416);
        }

        //判断媒资信息
        RestResponse<MediaDTO> response = mediaApiAgent.getMediaById4s(dto.getMediaId());
        if (!(response.isSuccessful())) {
            ExceptionCast.castWithCodeAndDesc(response.getCode(),response.getMsg());
        }
        // 判断媒资信息是否存在
        MediaDTO mediaDTO = response.getResult();
        if (ObjectUtils.isEmpty(mediaDTO)) {
            ExceptionCast.cast(ContentErrorCode.E_120417);
        }
        // 判断是否是同一家机构
        if (!(ObjectUtils.nullSafeEquals(mediaDTO.getCompanyId(),companyId))) {
            ExceptionCast.cast(CommonErrorCode.E_403000);
        }
        String mediaAuditStatus = mediaDTO.getAuditStatus();
        // 判断媒资审核状态
        if (!(AuditEnum.AUDIT_PASTED_STATUS.getCode().equals(mediaAuditStatus))) {
            ExceptionCast.cast(ContentErrorCode.E_120418);
        }
        // 3.将dto数据转为po数据并保存到teachplanmedia表中
        //     添加或修改
        //         如果存在：
        //             对课程计划的媒资信息进行修改：mediaId，mediaFileName
        //         如果不存在：
        //             课程计划和媒资信息的添加
        LambdaQueryWrapper<TeachplanMedia> teachplanMediaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanMediaQueryWrapper.eq(TeachplanMedia::getTeachplanId,dto.getTeachplanId());
        teachplanMediaQueryWrapper.eq(TeachplanMedia::getCourseId,courseId);
        TeachplanMedia teachplanMedia = teachplanMediaService.getOne(teachplanMediaQueryWrapper);
        boolean result = false;
        if (ObjectUtils.isEmpty(teachplanMedia)) {
            // 添加操作
            teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setTeachplanId(dto.getTeachplanId());
            teachplanMedia.setCourseId(courseId);
            teachplanMedia.setMediaFilename(mediaDTO.getFilename());
            result = teachplanMediaService.save(teachplanMedia);
        } else {
            // 修改操作: 改为UpdateWrapper
            teachplanMedia.setMediaFilename(mediaDTO.getFilename());
            teachplanMedia.setMediaId(dto.getMediaId());
            result = teachplanMediaService.updateById(teachplanMedia);
        }
        // 4.判断保存数据的结果并返回
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120411);
        }
        TeachplanMediaDTO resultDTO = TeachplanMediaConvert.INSTANCE.entity2dto(teachplanMedia);
        return resultDTO;
    }
}
